<template>
<div id="chat-app">
    <UserList v-if="!bool" :userlist="userList"/>
    <ChooseUser
        v-else-if="bool && !isChat"
        :friends="friends"
        :unreceivedNameList="unreceivedNameList"
        @close="closeFriendList"
        @tochat="toChat"
    />
    <Chat v-else :chatuser="chatUser" :news="newMsg" @back="closeChat"/>
</div>
</template>

<script>
import UserList from "./components/UserList"
import ChooseUser from "./components/ChooseUser"
import Chat from "./components/Chat"
export default {
    data() {
        return {
            userList: [],
            friends: [],
            bool: false,
            userSelf: null,
            isChat: false,
            chatUser: null,
            newMsg: null,
            unreceivedNameList: [],
        }
    },
    beforeMount() {
        this.init()
    },
    mounted() {
        this.getUserList()
        this.socket.on("login", data => {
            if(data.status === 200) {
                this.bool = true
                this.socket.emit("users")
            } else {
                console.log(data);
            }
        })

        this.socket.on("users", users => {
            this.friends = users
        })

        // 接收未读消息
        this.socket.on("unreceived", data => {
            console.log("接收未读消息：", data);
            data.forEach(item => {
                this.unreceivedNameList.push(item.from)
                item.from = this.userObj[item.from]
                item.to = this.userObj[item.to]
                let chatRecord = JSON.parse(localStorage.getItem(`chatUserMsg-${this.$root.userSelf.username}-${item.from.username}`)) || []
                // 判断是否有重复时间戳
                let bool = chatRecord.some(local => {
                    return local.chatTime === item.chatTime
                })
                // 防止重复本地存储
                if(bool) {
                    bool = false
                } else {
                    chatRecord.push(item)
                    localStorage.setItem(`chatUserMsg-${this.$root.userSelf.username}-${item.from.username}`, JSON.stringify(chatRecord))
                }
            });
        })

        // 接收最新消息
        this.socket.on("msgInfo", data => {
            let currentUser = JSON.parse(localStorage.getItem("currentUser"))
            console.log("接收最新消息：", data);
            if((this.isChat &&  this.chatUser.username === data.from.username) || (data.to.username === this.chatUser.username && data.to.isGroup)) {
                // this.newMsg.push(data)
                console.log("在线（聊天窗中）。。。");
                this.newMsg = data
            } else {
                console.log("不在聊天窗中。。。");
                let msg = JSON.parse(localStorage.getItem(`chatUserMsg-${this.$root.userSelf.username}-${data.from.username}`)) || []
                msg.push(data)
                this.unreceivedNameList.push(data.from.username)
                localStorage.setItem(`chatUserMsg-${this.$root.userSelf.username}-${data.from.username}`, JSON.stringify(msg))
                this.unreceivedNameList.push(data.from.username)
            }
        })

        this.socket.on("logout", data => {
            console.log(data)
            this.socket.disconnect()
            this.bool = false
        })

        this.socket.on("disconnect", data => {
            console.log('断开连接...')
        })
    },
    methods: {
        // socket 连接
        init() {
            // console.log(this.socket);
            this.socket.on("connect", () => {
                console.log("客户端已连接...");
            })
            this.socket.on("addUser", data => {
                console.log(data);
            })
        },

        toChat(data) {
            this.isChat = data.flag
            this.chatUser = data.chatUser
        },

        closeFriendList(data) {
            this.bool = data
        },

        closeChat(data) {
            this.isChat = data
        },

        // 获取用户
        async getUserList() {
            let res = await this.axios.get("http://localhost:3000/userList")
            // let res = await this.axios.get("/userList")
            this.userList = res.data
        }
    },
    computed: {
        userObj() {
            let obj = {}
            this.friends.forEach(item => {
                obj[item.username] = item
            })
            return obj
        }
    },
    components: {
        UserList,
        ChooseUser,
        Chat
    }
}
</script>